const Response = require("../../class/Response");
const LocalEvent = require("../../class/LocalEvent");

// 客户端连接成功
WSS.on('connection', async (thisClient)=>{
    // bds 功能初始化
    let {req, res} = await thisClient.sendJsonAsync(new Response().setUrl("/bds/init"));
    if (req?.body?.statusCode != 0 ){return false;}

    thisClient.bds ??= {
        syncType: 'sub',      // 'main' or 'sub'
        uuid: '',             // BDS唯一识别名
        ip: '',               // 
        port: 19132           // 
    };

    if (req.data.bds.syncType == 'main'){
        if (WSS.clientsManager.getClientMainBDS() != undefined){
            WSS.logger.error('此服配置文件为主服, 但WS服务端已经有一个主服在线。 WS协调服务端只允许唯一主服, 请修改配置文件 | ' + thisClient.name);
        }
    }

    thisClient.bds = {...req.data.bds};
    WSS.logger.info(`>> 注册BDS: ${thisClient.name} | 同步属性: ${thisClient.bds.syncType} | ip: ${thisClient.bds.ip} | port: ${thisClient.bds.port}`);
    WSS.logger.info(`>> 当前WS连接(${WSS.clientsManager.length}): ${WSS.clientsManager.getOnlineClientsName()}`);
    WSS.clientsManager.broadcastLogger(`>> 注册BDS: ${thisClient.name} | 同步属性: ${thisClient.bds.syncType} | ip: ${thisClient.bds.ip} | port: ${thisClient.bds.port}`);
    WSS.clientsManager.broadcastLogger(`>> 当前WS连接(${WSS.clientsManager.length}): ${WSS.clientsManager.getOnlineClientsName()}`);

    // 发送当前客户端注册初始化结果
    thisClient.sendJson(Response.replyTo(req)
        .setUrl('/bds/init/result')
        .setStatusCode(0)
        .setStatusMessage(`${thisClient.name} 已注册到WS服务端`)
        .setData(thisClient.getClientInfo())
    );

    // 发送客户端连接事件
    WSS.clientsManager.broadcastJson(new Response()
        .setUrl(CONSTANTS.EVENT.CLIENT_CONNECT)
        .setSourceId(thisClient.id)
        .setSourceBdsUuid(thisClient.bds.uuid)
        .setSourceBdsServerName(thisClient.name)
        .setData(thisClient.getClientInfo())
    );

    // 本地事件
    WSS.api.listener.emit(CONSTANTS.EVENT.CLIENT_CONNECT, new LocalEvent()
        .setSourceId(thisClient.id)
        .setSourceBdsUuid(thisClient.bds.uuid)
        .setSourceBdsServerName(thisClient.name)
        .setStatusCode(0)
        .setStatusMessage(``)
        .setData(thisClient.getClientInfo()).json
    );
    

    // 更新客户端的在线玩家信息(一共四处, bds连接断连，玩家登录退出)
    WSS.clientsManager.broadcastJson(new Response()
        .setUrl('/bds/onlineInfo')
        .setSourceId(thisClient.id)
        .setSourceBdsUuid(thisClient.bds.uuid)
        .setSourceBdsServerName(thisClient.name)
        .setStatusCode(0)
        .setStatusMessage("更新客户端的在线玩家信息")
        .setData({
            onlineClientsInfo: WSS.clientsManager.getOnlineClientsInfo(),
            onlinePlayersInfo: WSS.clientsManager.onlinePlayers
        })
    );
});

// 定时更新BDS的mspt等基础信息
setInterval(()=>{
    WSS.clientsManager.forEach(client => {
        if (client.userType != 'bds'){return;}
        client.sendJson(new Response()
            .setUrl('/bds/getThisBdsInfo')
            .setStatusCode(0)
            .setStatusMessage("获取各BDS的mspt等基础信息"),
            (req, res) =>{
                if (req.body.statusCode != 0){return;}
                client.bds = {...client.bds, ...req.body.data.bds};
            }
        );
    });
},15000);